package cc.fs.study.Image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import java.io.ByteArrayOutputStream;

/**
 * 图片压缩处理
 * Created by fostion on 6/14/16.
 */
public class ImageUtil {

    /**
     * 尺寸压缩
     */
    public static void zoomImage(String path) {
        //压缩图片长宽 避免oom
        int maxWdith = 720;
        BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
        bitmapFactoryOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, bitmapFactoryOptions);
        int scale = (int) calculateInSampleSize(bitmapFactoryOptions, maxWdith, maxWdith);
        bitmapFactoryOptions.inSampleSize = scale;
        bitmapFactoryOptions.inJustDecodeBounds = false;
        BitmapFactory.decodeFile(path, bitmapFactoryOptions);
    }

    /***
     * 图片的缩放方法
     */
    public static Bitmap zoomImage(Bitmap bgimage) {
        int maxWidth = 720;
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) maxWidth) / width;
        float scaleHeight = ((float) maxWidth) / height;
        float scale = (scaleWidth > scaleHeight) ? scaleWidth:scaleHeight;
        // 缩放图片动作
        matrix.postScale(scale, scale);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    /**
     * 计算变化规模
     */
    private static float calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        float height = (float) options.outHeight;
        float width = (float) options.outWidth;
        float inSampleSize = 1;

        //比最大尺寸小的图片不处理
        if (height > reqHeight || width > reqWidth) {
            float heightRatio = Math.round(height / reqHeight);
            float widthRatio = Math.round(width / reqWidth);

            inSampleSize = (heightRatio > widthRatio) ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * 质量压缩图片
     */
    public byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        return baos.toByteArray();
    }

}
